package com.heimo.babyage;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.heimo.babyage.billing.IabHelper;
import com.heimo.babyage.billing.IabResult;
import com.heimo.babyage.billing.Inventory;
import com.heimo.babyage.billing.Purchase;
import com.heimo.babyage.core.LogHelper;
import com.heimo.babyage.core.PrefHelper;

public class SponsorActivity extends BasicActivity {
	private static final String TAG = "SponsorActivity";
	private TextView tvTitle, tvDetail;
	private ProgressDialog progressDialog;
	private Button btnSponsor, btnClose;

	// Billing related variables
	private IabHelper mHelper;
	private static final String SKU_SPONSOR = "sponsor";
	// (arbitrary) request code for the purchase flow
	private static final int RC_REQUEST = 10001;
	private boolean mhasSponsor = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sponsor);
		fnSetUpBilling();
		fnInitUI();

	}

	private void fnInitUI() {
		tvTitle = (TextView) findViewById(R.id.title_sponsor);
		tvDetail = (TextView) findViewById(R.id.title_sponsor_detail);
		btnSponsor = (Button) findViewById(R.id.btn_sponsor);
		btnClose = (Button) findViewById(R.id.btn_close);

		btnSponsor.setEnabled(false);

		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/orbitron-bold.otf");
		if(tf!=null){
			tvTitle.setTypeface(tf);
			btnSponsor.setTypeface(tf);
			btnClose.setTypeface(tf);
		}
	}

	private void fnUpdateSponsoredUI() {
		String txtThankls = this.getString(R.string.lab_thanks);
		tvDetail.setText(txtThankls);
		btnSponsor.setEnabled(false);
	}

	private void fnSetUpBilling() {
		String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2ZgRaDtRz9j+iogKLWOndmMv3ssOGcvznimBZoNcS9d1KdMacErZxIVmY+OVakCreLz+LuaiMi8nL0lOVhCxwEUz6qbUGtQt9hyYJ/oF7J72HjXtBc2qXgMZxlDydPny+OvpHIPDkp7J58XB1plzRvpWPtJhDVD7jLJcXobiotjAZ1/k5B6ad5aoqw1yMrYXdgQMimFIj4quDP0UxZmNpMPgviFGObzOXsrqfWPdjswklr9bWypBtYHbBcklt2Z1JppBEF2wAARyhveTMOM+WProWqB2KolzvR/xqLB4+u+aXx8Lba4fAyIq0QDjzFtJT/Lw+N1TNnJ8m6jDdbCvWQIDAQAB";
		LogHelper.log(TAG, "Creating IAB helper.");
		mHelper = new IabHelper(this, base64EncodedPublicKey);

		// enable debug logging (for a production application, you should set
		// this to false).
		mHelper.enableDebugLogging(true);

		setWaitScreen(true);
		// Start setup. This is asynchronous and the specified listener
		// will be called once setup completes.
		LogHelper.log(TAG, "Starting setup.");
		mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
			public void onIabSetupFinished(IabResult result) {
				setWaitScreen(false);
				LogHelper.log(TAG, "Setup finished.");
				if (!result.isSuccess()) {
					toast("Problem setting up in-app billing: " + result);
					return;
				}
				// Check if sponsored.
				LogHelper.log(TAG, "Setup successful. Querying inventory.");
				mHelper.queryInventoryAsync(mGotInventoryListener);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogHelper.log(TAG, "onActivityResult(" + requestCode + "," + resultCode
				+ "," + data);

		// Pass on the activity result to the helper for handling
		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			// not handled, so handle it ourselves (here's where you'd
			// perform any handling of activity results not related to in-app
			// billing...
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			LogHelper.log(TAG, "onActivityResult handled by IABUtil.");
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		// this.fnExit();
	}

	@Override
	public void onStop() {
		super.onStop();
		// this.fnExit();
	}

	@Override
	public void onDestroy() {

		if (progressDialog != null) {
			progressDialog.dismiss();
		}

		super.onDestroy();

		// very important:
		LogHelper.log(TAG, "Destroying helper.");
		if (mHelper != null)
			mHelper.dispose();
		mHelper = null;
	}

	public void fnSponsor(View v) {
		LogHelper.log(TAG,
				"Upgrade button clicked; launching purchase flow for upgrade.");
		setWaitScreen(true);
		String payload = "";

		mHelper.launchPurchaseFlow(this, SKU_SPONSOR, RC_REQUEST,
				mPurchaseFinishedListener, payload);
	}

	private void setWaitScreen(boolean b) {
		if (b) {
			if (progressDialog == null) {
				progressDialog = ProgressDialog.show(this, "",
						"Loading. Please wait...", true);
			} else {
				progressDialog.show();
			}
		} else {
			progressDialog.dismiss();
		}
	}

	public void fnClose(View v) {
		this.fnExit();
	}

	// Listener that's called when we finish querying the items and
	// subscriptions we own
	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result,
				Inventory inventory) {
			LogHelper.log(TAG, "Query inventory finished.");
			if (result.isFailure()) {
				toast("Failed to query inventory: " + result);
				return;
			}

			LogHelper.log(TAG, "Query inventory was successful.");

			/*
			 * Check for items we own. Notice that for each purchase, we check
			 * the developer payload to see if it's correct! See
			 * verifyDeveloperPayload().
			 */

			// Do we have the premium upgrade?
			Purchase premiumPurchase = inventory.getPurchase(SKU_SPONSOR);
			mhasSponsor = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
			LogHelper.log(TAG, "User has sponsored ? "
					+ (mhasSponsor ? "Yes" : "No"));
			setWaitScreen(false);
			if (mhasSponsor == true) {
				fnSetSponsored();
				fnUpdateSponsoredUI();
			} else {
				btnSponsor.setEnabled(true);
			}
			LogHelper.log(TAG,
					"Initial inventory query finished; enabling main UI.");
		}
	};

	private boolean verifyDeveloperPayload(Purchase p) {
		String payload = p.getDeveloperPayload();

		/*
		 * TODO: verify that the developer payload of the purchase is correct.
		 * It will be the same one that you sent when initiating the purchase.
		 * 
		 * WARNING: Locally generating a random string when starting a purchase
		 * and verifying it here might seem like a good approach, but this will
		 * fail in the case where the user purchases an item on one device and
		 * then uses your app on a different device, because on the other device
		 * you will not have access to the random string you originally
		 * generated.
		 * 
		 * So a good developer payload has these characteristics:
		 * 
		 * 1. If two different users purchase an item, the payload is different
		 * between them, so that one user's purchase can't be replayed to
		 * another user.
		 * 
		 * 2. The payload must be such that you can verify it even when the app
		 * wasn't the one who initiated the purchase flow (so that items
		 * purchased by the user on one device work on other devices owned by
		 * the user).
		 * 
		 * Using your own server to store and verify developer payloads across
		 * app installations is recommended.
		 */

		return true;
	}

	private void fnSetSponsored() {
		PrefHelper.fnSaveSponsor(this);
	}

	// Callback for when sponsor is finished
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			LogHelper.log(TAG, "Purchase finished: " + result + ", purchase: "
					+ purchase);
			if (result.isFailure()) {
				toast("Error purchasing: " + result);
				setWaitScreen(false);
				return;
			}
			if (!verifyDeveloperPayload(purchase)) {
				toast("Error purchasing. Authenticity verification failed.");
				setWaitScreen(false);
				return;
			}

			LogHelper.log(TAG, "Purchase successful.");

			if (purchase.getSku().equals(SKU_SPONSOR)) {
				// bought the premium upgrade!
				LogHelper.log(TAG,
						"Purchase for sponsor is done. Congratulating user.");
				fnSetSponsored();
				toast("Thank you for sponsoring to Baby Age!");
				mhasSponsor = true;
				setWaitScreen(false);
				fnUpdateSponsoredUI();
			}
		}
	};
}
